package com.walkline.screen;

import java.util.Hashtable;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.util.StringProvider;

import com.walkline.util.Enumerations.Friendshitp;
import com.walkline.util.Enumerations.RefreshAction;
import com.walkline.util.Enumerations.StatusCount;
import com.walkline.util.Function;
import com.walkline.util.container.ForegroundManager;
import com.walkline.util.container.UserInfoListStyleButtonSet;
import com.walkline.util.ui.UserInfoListStyleButtonField;
import com.walkline.weibo.WeiboSDK;
import com.walkline.weibo.inf.User;

/**
 * 个人首页窗口
 */
public class HomePageMainScreen extends MainScreen
{
	private WeiboSDK _weibo;
	private User _user;

	private ForegroundManager _foreground=new ForegroundManager(0);
	private UserInfoListStyleButtonSet _headSet = new UserInfoListStyleButtonSet();
	private UserInfoListStyleButtonSet _infoSet = new UserInfoListStyleButtonSet();
	private UserInfoListStyleButtonSet _listSet = new UserInfoListStyleButtonSet();

	private String _page_count = "20"; //WeiboSDK.STATUS_COUNT;
	private String _current_page = "1";
	private String _current_cursor = "0";
	private String _max_id = "0";
	private boolean _is_myself = false;

	public HomePageMainScreen(WeiboSDK weibo, final Hashtable params)
	{
		super(NO_VERTICAL_SCROLL | USE_ALL_HEIGHT | NO_SYSTEM_MENU_ITEMS);

		_weibo = weibo;

		_page_count = StatusCount.choicesStatusCount[weibo.getAppConfig().getStatusCount()];

		HorizontalFieldManager hfm = new HorizontalFieldManager(FIELD_HCENTER);
		hfm.add(new LabelField("个人信息"));
		setTitle(hfm);

		createUI();

		add(_foreground);

		UiApplication.getUiApplication().invokeLater(new Runnable()
		{
			public void run() {getUserInfo(params);}
		});
	}

	public HomePageMainScreen(WeiboSDK weibo, final User user)
	{
		super(NO_VERTICAL_SCROLL | USE_ALL_HEIGHT | NO_SYSTEM_MENU_ITEMS);

		_weibo = weibo;
		//_user = user;

		HorizontalFieldManager hfm = new HorizontalFieldManager(FIELD_HCENTER);
		hfm.add(new LabelField(user.getScreenName() + "的主页"));
		setTitle(hfm);

		createUI();

		add(_foreground);

		UiApplication.getUiApplication().invokeLater(new Runnable()
		{
			public void run() {refreshUI(user);}
		});
	}

	private void getUserInfo(Hashtable params)
	{
		RefreshContentsScreen popupScreen = new RefreshContentsScreen(_weibo, params, RefreshAction.USERINFO);
		UiApplication.getUiApplication().pushModalScreen(popupScreen);

		User userInfo = popupScreen.getUserInfo();

		if (popupScreen != null) {popupScreen = null;}
		if (userInfo != null) {refreshUI(userInfo);}
	}

	private void createUI()
	{
		UserInfoListStyleButtonField item;

		item = new UserInfoListStyleButtonField(true, "", "", "");
		_headSet.add(item);

		item = new UserInfoListStyleButtonField("注册时间", "无", false);
		item.setEnabled(false);
		_infoSet.add(item);

		item = new UserInfoListStyleButtonField("城市", "无", false);
		item.setEnabled(false);
		_infoSet.add(item);

		item = new UserInfoListStyleButtonField(false, "个人介绍", null, "无");
		item.setEnabled(false);
		_infoSet.add(item);

		item = new UserInfoListStyleButtonField("微博", "0", true);
		_listSet.add(item);

		item = new UserInfoListStyleButtonField("好友", "0", true);
		_listSet.add(item);

		item = new UserInfoListStyleButtonField("粉丝(互粉)", "0", true);
		_listSet.add(item);

		item = new UserInfoListStyleButtonField("收藏", "0", true);
		_listSet.add(item);

		//item = new UserInfoListStyleButtonField("话题：", "0", 0, true);
		//_listSet.add(item);

		_foreground.add(_headSet);
		_foreground.add(_infoSet);
		_foreground.add(_listSet);
	}
	
	private void refreshUI(final User user)
	{
		HorizontalFieldManager hfm = new HorizontalFieldManager(FIELD_HCENTER);
		hfm.add(new LabelField(user.getScreenName()+" 的主页"));
		setTitle(hfm);

		_user = user;
		_is_myself = _weibo.getUserIdStr().equals(user.getIdStr());

		try {
			UserInfoListStyleButtonField item = (UserInfoListStyleButtonField) _headSet.getField(0);

			item.setAvatarData(user.getAvatarIconData()); //小头像
			item.setTitleText(user.getScreenName()); //姓名
			item.setDescription(user.getGender()); //性别
			if (!isMyself())
			{
				int friendshipType = user.isFollowing() && user.isFollowMe() ? Friendshitp.FOLLOWED : user.isFollowing() ? Friendshitp.FOLLOWING : Friendshitp.FOLLOWME;

				item.setFriendship(friendshipType);
			}
			item.setChangeListener(null);
			item.setChangeListener(new FieldChangeListener()
			{
				public void fieldChanged(Field field, int context)
				{
					UiApplication.getUiApplication().pushScreen(new ShowPreviewImagesFullScreen(_weibo, user));
				}
			});

			//注册时间
			item = (UserInfoListStyleButtonField) _infoSet.getField(0);
			item.setValueText(user.getCreatedAtLong());

			//城市
			item = (UserInfoListStyleButtonField) _infoSet.getField(1);
			item.setValueText(user.getLocation());

			//个人简介
			item = (UserInfoListStyleButtonField) _infoSet.getField(2);
			item.setDescription(user.getDescription().equals("") ? "无" : user.getDescription());

			//微博
			item = (UserInfoListStyleButtonField) _listSet.getField(0);
			item.setValueText(user.getStatusesCount() + "");
			item.setChangeListener(null);
			item.setChangeListener(new FieldChangeListener()
			{
				public void fieldChanged(Field field, int context)
				{
					Hashtable params = new Hashtable();

					params.put("title", user.getScreenName() + " 的微博");
					params.put("uid", user.getIdStr());
					params.put("count", _page_count);
					params.put("page", _current_page);
					params.put("max_id", _max_id);

					UiApplication.getUiApplication().pushScreen(new ShowStatusesMainScreen(_weibo, params, RefreshAction.USERTIMELINE));
				}
			});
			if (!isMyself()) {item.setEnabled(false);}

			//关注
			item = (UserInfoListStyleButtonField) _listSet.getField(1);
			item.setValueText(user.getFriendsCount() + "");
			item.setChangeListener(null);
			item.setChangeListener(new FieldChangeListener()
			{
				public void fieldChanged(Field field, int context)
				{
					Hashtable params = new Hashtable();

					params.put("title", user.getScreenName() + " 的好友");
					params.put("uid", user.getIdStr());
					params.put("count", _page_count);
					params.put("cursor", _current_cursor);

					UiApplication.getUiApplication().pushScreen(new ShowFriendshipMainScreen(_weibo, params, RefreshAction.USERLISTFRIENDS));
				}
			});
			if (!isMyself()) {item.setEnabled(false);}

			//粉丝(互粉)
			item = (UserInfoListStyleButtonField) _listSet.getField(2);
			item.setValueText(user.getFollowersCount() + "(" + user.getBiFollowersCount() + ")");
			item.setChangeListener(null);
			item.setChangeListener(new FieldChangeListener()
			{
				public void fieldChanged(Field field, int context)
				{
					Hashtable params = new Hashtable();

					params.put("title", user.getScreenName() + " 的粉丝");
					params.put("uid", user.getIdStr());
					params.put("count", _page_count);
					params.put("cursor", _current_cursor);

					UiApplication.getUiApplication().pushScreen(new ShowFriendshipMainScreen(_weibo, params, RefreshAction.USERLISTFOLLOWERS));
				}
			});
			if (!isMyself()) {item.setEnabled(false);}

			//收藏
			item = (UserInfoListStyleButtonField) _listSet.getField(3);
			item.setValueText(user.getFavouritesCount() + "");
			item.setChangeListener(null);
			item.setChangeListener(new FieldChangeListener()
			{
				public void fieldChanged(Field field, int context)
				{
					UiApplication.getUiApplication().pushModalScreen(new ShowFavoriteCatalogsMainScreen(_weibo));
				}
			});
			if (!isMyself()) {item.setEnabled(false);}

			/*
			link = (HomePageListStyleButtonField) _buttonSet2.getField(4);
			link.setValueText(user.getTrends().size()+""); //话题
			link.setChangeListener(null);
			link.setChangeListener(new FieldChangeListener()
			{
				public void fieldChanged(Field field, int context)
				{
					Vector trends = user.getTrends();
					StringBuffer sb=new StringBuffer();
					
					sb.append(user.getScreenName()+"关注的话题");
					sb.append("\n\n");
					for(int i=0; i<trends.size(); i++)
					{
						sb.append(i+1+": ");
						sb.append(((UserTrend) trends.elementAt(i)).getHotword());
						sb.append("\n");
					}
					
					Function.errorDialog(sb.toString());
				}
			});
			*/
		} catch (Exception e) {Function.errorDialog(e.toString());}
	}

	private boolean isMyself() {return _is_myself;}

	private void createFriendship()
	{
		if (_listSet.getFieldCount() > 0)
		{
			//UserInfoListStyleButtonField item = (UserInfoListStyleButtonField) _listSet.getFieldWithFocus();

			RefreshContentsScreen popupScreen = new RefreshContentsScreen(_weibo, _user.getIdStr(), RefreshAction.CREATEFRIENDSHIP);
			UiApplication.getUiApplication().pushModalScreen(popupScreen);

			User user = popupScreen.getUserInfo();

			if (popupScreen != null) {popupScreen = null;}
			if (user != null)
			{
				Function.errorDialog("已成功关注 " + user.getScreenName());

				Hashtable params = new Hashtable();
				params.put("uid", user.getIdStr());
				params.put("screen_name", "");
				getUserInfo(params);
			}
		}
	}

	private void destroyFriendship(int action)
	{
		if (_listSet.getFieldCount() > 0)
		{
			RefreshContentsScreen popupScreen = new RefreshContentsScreen(_weibo, _user.getIdStr(), action);
			UiApplication.getUiApplication().pushModalScreen(popupScreen);

			User user = popupScreen.getUserInfo();

			if (popupScreen != null) {popupScreen = null;}
			if (user != null)
			{
				String tips = "";

				switch (action)
				{
					case RefreshAction.DESTROYFOLLOWER:
						tips = "已成功移除粉丝 ";
						break;
					case RefreshAction.DESTROYFRIENDSHIP:
						tips = "已成功取消关注 ";
						break;
				}

				Function.errorDialog(tips + user.getScreenName());

				Hashtable params = new Hashtable();
				params.put("uid", user.getIdStr());
				params.put("screen_name", "");
				getUserInfo(params);
			}
		}
	}

	MenuItem menuRefreshInformation = new MenuItem(new StringProvider("刷新"), 100, 10)
	{
		public void run() {refreshUI(_user);}
	};

	MenuItem menuCreateFriendship = new MenuItem(new StringProvider("加关注"), 100, 20)
	{
		public void run() {createFriendship();}
	};

	MenuItem menuDestroyFriendship = new MenuItem(new StringProvider("取消关注"), 100, 30)
	{
		public void run()
		{
			Dialog askDialog = new Dialog(Dialog.D_YES_NO, "是否取消关注用户 " + _user.getScreenName() + "？", Dialog.NO, Bitmap.getPredefinedBitmap(Bitmap.QUESTION), 0);

			UiApplication.getUiApplication().pushModalScreen(askDialog);
			if (askDialog.getSelectedValue() == Dialog.YES) {destroyFriendship(RefreshAction.DESTROYFRIENDSHIP);}
		}
	};

	MenuItem menuDestroyFollower = new MenuItem(new StringProvider("移除粉丝"), 100, 40)
	{
		public void run()
		{
			Dialog askDialog = new Dialog(Dialog.D_YES_NO, "是否移除粉丝 " + _user.getScreenName() + "？", Dialog.NO, Bitmap.getPredefinedBitmap(Bitmap.QUESTION), 0);

			UiApplication.getUiApplication().pushModalScreen(askDialog);
			if (askDialog.getSelectedValue() == Dialog.YES) {destroyFriendship(RefreshAction.DESTROYFOLLOWER);}
		}
	};

	protected void makeMenu(Menu menu, int instance)
	{
		//menu.add(menuRefreshInformation);
		//menu.addSeparator();
		if (!isMyself())
		{
			menu.add(menuCreateFriendship);
			menu.add(menuDestroyFriendship);
			menu.addSeparator();
			menu.add(menuDestroyFollower);
			menu.addSeparator();
		}

		super.makeMenu(menu, instance);
	};
}